package com.linqi.freebie.http.ktorClientCio


import com.linqi.freebie.http.ktorClientCio.interceptor.*
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.header
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.*

object HttpClientManager {
    private var clientInstance: HttpClient? = null
    private val customInterceptors = mutableListOf<HttpInterceptor>()

    fun addInterceptor(interceptor: HttpInterceptor): HttpClientManager {
        customInterceptors.add(interceptor)
        return this
    }

    fun getClient(): HttpClient {
        return clientInstance ?: createClient().also { clientInstance = it }
    }

    private fun createClient(): HttpClient {
        return HttpClient(CIO) {
            install(ContentNegotiation) {
                json(Json {
                    ignoreUnknownKeys = true
                    isLenient = true
                    prettyPrint = true
                })
            }

            install(HttpTimeout) {
                requestTimeoutMillis = 15_000
                connectTimeoutMillis = 10_000
                socketTimeoutMillis = 15_000
            }



            // 动态拦截器插件
            if (customInterceptors.isNotEmpty()) {
                install(InterceptorChainPlugin(customInterceptors))
            }

            // 可以在这里添加其他基本配置
            // 例如默认请求头、日志等
            defaultRequest {
                header("Accept", "application/json")
            }
        }
    }

    fun close() {
        clientInstance?.close()
        clientInstance = null
    }
}


